package com.chucknorris.android.adapter;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.CursorAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.chucknorris.android.R;
import com.chucknorris.android.db.ChuckColumns;
import com.chucknorris.android.db.ChuckQuery;
import com.chucknorris.android.model.Chuck;

public class ChuckAdapter extends CursorAdapter {

	private LayoutInflater mInflater;

	public ChuckAdapter(Context context, Cursor c) {
		super(context, c, false);
		mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

	}

	@Override
	public void bindView(View view, final Context context, final Cursor cursor) {
		final ChuchViewHolder listItem = (ChuchViewHolder) view.getTag();
		final String warrantyText = getCursor().getString(ChuckQuery.TOPIC);
		final long id = getCursor().getLong(ChuckQuery._ID);
//		try {
//			listItem.txt.setText(SimpleCrypto.decrypt(ChuckActivity.SEED, warrantyText));
//		} catch (Exception e) {
//			e.printStackTrace();
//		}
		listItem.txt.setText(warrantyText);
		listItem.image.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Log.e("safdsdf", "" + id);
				ContentValues values = new ContentValues();
				values.put(ChuckColumns.ISLIKE.getName(), String.valueOf(0));
				if (1 == context.getContentResolver().update(Chuck.CONTENT_URI, values, ChuckColumns._ID.getName() + " =? ",
						new String[] { String.valueOf(id) })) {
					cursor.requery();
				}
			}
		});

	}

	@Override
	public View newView(Context context, Cursor cursor, ViewGroup parent) {
		View view = mInflater.inflate(R.layout.list_item, null);
		final ChuchViewHolder listItem = new ChuchViewHolder();
		listItem.txt = (TextView) view.findViewById(R.id.text_topic);
		listItem.image = (ImageView) view.findViewById(R.id.delete);

		view.setTag(listItem);
		return view;

	}

	public class ChuchViewHolder {
		TextView txt;
		ImageView image;

	}

}
